package com.bwda.dsrs.systemservice.util.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.bwda.dsrs.base.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * simple introduction
 *
 * @author yanyuemei
 * @date
 */
public class JwtTokenUtil {
    private static Logger logger = LoggerFactory.getLogger(JwtTokenUtil.class);
    private static final int BEARER_BEGIN_INDEX = 7;

    /**
     * jwt token 密钥，主要用于token解析，签名验证
     */
    @Value("${spring.security.oauth2.jwt.signingKey}")
    private String signingKey;

    /**
     * Authorization认证开头是"bearer "
     */
    public static Jwt getJwt(String authentication) {
        return JwtHelper.decode(StringUtils.substring(authentication, BEARER_BEGIN_INDEX));
    }

    /**
     * 过期时间5分钟
     */
    private static final long EXPIRE_TIME = 5 * 60 * 1000;



    /**
     * 获得token中的信息无需secret解密也能获得
     *
     * @return token中包含的用户名
     */

    public static String getUserCode(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map userDetail = (Map) JSON.parseObject(jwt.getClaim("userDetail").asString());
            return (String) userDetail.get("userCode");
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getUserName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map userDetail = (Map) JSON.parseObject(jwt.getClaim("userDetail").asString());
            return (String) userDetail.get("userName");
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getOrgId(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map userDetail = (Map) JSON.parseObject(jwt.getClaim("userDetail").asString());
            return String.valueOf(userDetail.get("orgId"));
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getOrgName(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map userDetail = (Map) JSON.parseObject(jwt.getClaim("userDetail").asString());
            return (String) userDetail.get("orgName");
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    public static String getOrgAdminCode(String token) {
        try {
            DecodedJWT jwt = JWT.decode(token);
            Map userDetail = (Map) JSON.parseObject(jwt.getClaim("userDetail").asString());
            return (String) userDetail.get("orgAdminCode");
        } catch (JWTDecodeException e) {
            return null;
        }
    }


    /**
     * 生成签名,5min后过期
     *
     * @param userName 用户名
     * @param secret   用户的密码
     * @return 加密的token
     */
    public static String sign(String userCode, String userName, String orgId, String orgName, String orgAdminCode, String secret) {
        Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        Algorithm algorithm = Algorithm.HMAC256(secret);
        Map<String, Object> userMap = new HashMap<>(16);
        userMap.put("userCode", userCode);
        userMap.put("userName", userName);
        userMap.put("orgId", orgId);
        userMap.put("orgName", orgName);
        userMap.put("orgAdminCode", orgAdminCode);
        // 附带username信息
        return JWT.create()
                .withClaim("userDetail", JSONObject.toJSONString(userMap))
                .withExpiresAt(date)
                .sign(algorithm);
    }

    public static void main(String[] args) {
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1uEaF551xc8kasFB92siwSm19FrhwUwGqaGthI";
        Jwt jwt = JwtHelper.decode(token);
        JSONObject json = JSON.parseObject(jwt.getClaims());
        System.out.println(json.get("userCode"));
    }
}
